package com.bridgetree.jubaocrm.ui;

import java.util.Calendar;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.JsonObjectPostRequest;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.LoginInterface;

/**
 * 添加事务提醒
 */
public class AddTransactionActivity extends Activity {

	private Context mContext;
	private final String tag = "AddTransactionActivity";
	private LoginInterface mLoginInterface;
	private InputMethodManager mInputMethodManager;
	private Button data_title_ed;
	private EditText tv_text_ed;
	
	private String user_id = "";
	private String token = "";

	private SharedPreferences prefs;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.transaction_edit);
		mContext = this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(tag, "intent is null");
			return;
		}
		mInputMethodManager = (InputMethodManager) this
				.getSystemService(Context.INPUT_METHOD_SERVICE);

		prefs = PreferenceManager
				.getDefaultSharedPreferences(AddTransactionActivity.this);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, "");
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");
		
		TextView xm_sp_tv_title = (TextView) findViewById(R.id.xm_sp_tv_title);
		data_title_ed = (Button) findViewById(R.id.data_title_ed);
		tv_text_ed = (EditText) findViewById(R.id.tv_text_ed);

		if (intent.getExtras() != null) {
			mLoginInterface = (LoginInterface) intent.getExtras()
					.getSerializable("LoginInterface");
		}
		xm_sp_tv_title.setText("新建事务提醒");
		data_title_ed.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				selectDate();
			}
		});
		findViewById(R.id.xm_sp_RelativeLayout_back).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						finish();
					}
				});

		findViewById(R.id.xm_sp_RelativeLayout_done).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						mInputMethodManager.hideSoftInputFromWindow(
								getCurrentFocus().getWindowToken(),
								InputMethodManager.HIDE_NOT_ALWAYS);
						getAdd();
					}
				});

	}

	String date = "";
	String time = "";
	Dialog Datedialog = null;
	Dialog Timedialog = null;

	private void selectDate() {
		Calendar calendar = Calendar.getInstance();
		DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker datePicker, int year, int month,
					int dayOfMonth) {
				date = year + "-" + (month + 1) + "-" + dayOfMonth;
				Timedialog.show();
			}
		};
		Datedialog = new DatePickerDialog(this, dateListener,
				calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH));
		Datedialog.show();

		TimePickerDialog.OnTimeSetListener timeListener = new TimePickerDialog.OnTimeSetListener() {

			@Override
			public void onTimeSet(TimePicker timerPicker, int hourOfDay,
					int minute) {
				time = " " + hourOfDay + ":" + minute;
				data_title_ed.setText(date + time);
			}
		};
		Timedialog = new TimePickerDialog(this, timeListener,
				calendar.get(Calendar.HOUR_OF_DAY),
				calendar.get(Calendar.MINUTE), false); // 是否为二十四制
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null
					&& getCurrentFocus().getWindowToken() != null) {
				mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}
	
	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title).setMessage(content)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
							LoginUtil.executeLoginFaild(mContext);
						}else if("添加成功！".equals(content)){
							Intent intent = new Intent();
							setResult(0x0002, intent);
							finish();
						}
						// TODO Auto-generated method stub
					}
				}).show();
	}
	
	private void getAdd() {
		String data = data_title_ed.getText().toString();
		String cont = tv_text_ed.getText().toString();
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else if (data.equals("")) {
			openDailog("输入提示", "请选择时间");
		} else if (cont.equals("")) {
			openDailog("输入提示", "请输入内容");
		} else if (cont.length()>70) {
			openDailog("输入提示", "内容必须少于70个字符");
		}else{
			final ProgressDialog progressDialog = ProgressDialog.show(mContext,
					"网络数据", "...Loading...");
			
			//reminder_time=2014-05-17 09:03
			//&content=wwwwwwwwwww
			//&user_id=cd34350bb2844077bfbd4abe5ec56f99
			//&token=b0a4c4f0cdcc4f668d0baf913fa8e463
			//&validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl


			HashMap<String, String> mMap = new HashMap<String, String>();
			mMap.put("reminder_time", data);
			mMap.put("content", cont);
			mMap.put("user_id", user_id);
			mMap.put("token", token);
			mMap.put("validation", CRMUserBaseInfo.kValication);
			String URL = Network.API_DOMAIN + "/reminder/new";

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(
					URL, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							try {
								if (progressDialog.isShowing()
										&& progressDialog != null) {
									progressDialog.dismiss();
								}
								System.out.println("添加事务  response=" + response);
								if (!response.isNull("errors")) {
									String errors = response.get("errors")
											.toString();
									if (errors.equals("[]")) {
										openDailog("网络提示", "添加成功！");
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
													.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
														.length(); i++) {
													JSONObject jsonObj2 = jsonArr
															.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
																.getString("desc");
														openDailog("失败提示", desc);
														mLoginError
																.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
																.getString("value");
														mLoginError
																.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (JSONException e) {
								if (progressDialog.isShowing()
										&& progressDialog != null) {
									progressDialog.dismiss();
								}
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							if (progressDialog.isShowing()
									&& progressDialog != null) {
								progressDialog.dismiss();
							}
							Toast.makeText(mContext, "网络未连接！",
									Toast.LENGTH_LONG).show();
						}
					}, mMap);
			requestQueue.add(jsonObjectPostRequest);
		}

	}


}
